﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Patterns.UnitOfWorkPattern.EF
{
    public class EfContext : DbContext, IDomainContext, IDomainContextUoWAccessor
    {
        private static readonly Dictionary<Type, bool> EntityTypes = new Dictionary<Type, bool>();

        protected static void RegisterEntityType(Type entityType)
        {
            EntityTypes.Add(entityType, true);
        }

        public static bool SupportsType(Type entityType)
        {
            if (!entityType.IsClass)
                return false;

            while (entityType != typeof(Object))
            {
                if (EntityTypes.ContainsKey(entityType))
                    return true;

                entityType = entityType.BaseType;
            }

            return false;
        }

        public EfContext(IMultiContextUnitOfWork uow, string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
            uow.RegisterContext(this);
        }

        public EfContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }

        public void ApplyChanges()
        {
            ((IObjectContextAdapter)this).ObjectContext.SaveChanges(System.Data.Entity.Core.Objects.SaveOptions.None);
        }

        public void Commit()
        {
            ((IObjectContextAdapter)this).ObjectContext.AcceptAllChanges();
        }

        public void Rollback()
        {
        }
    }
}
